<?php
/**
 * Created by PhpStorm.
 * User: cyc
 * Date: 2017/11/2
 * Time: 下午8:02
 */

class ChannelConfig extends ConfigDecorator
{
    const CACHE_KEY = 'channel_cache';
    const MODIFY_CACHE_KEY = 'channel_modify_cache_key';

    public function getChannelConfig()
    {
        $channelConfig = [];
        $channelConfig['name'] = $this->getName();
        $channelConfig['try'] = $this->getTry();
        if ($config = $this->_config->getConfig()) {
            foreach ($config as $key => $value) {
                if (strpos($key, MsggConfig::VERIFY_PARAM_PREFIX) === 0) {
                    unset($config[$key]);
                }
            }
            $channelConfig = array_merge($channelConfig, $config);
        }
        return $channelConfig;
    }

    public function getType()
    {
        return $this->_config->type;
    }


    public static function getChannelConfigs($type, $limit = [])
    {
        $level = self::util_array_get($limit, 'level', 0);
        $configs = array();
        $reloadFlag = true;
        //try to get configs from cache
        $cacheKey = implode('_', array(self::CACHE_KEY, $type));
        if (($cache = Yii::app()->cache) && ($cacheValue = $cache->get($cacheKey))) {
            if (($cacheConfigs = json_decode($cacheValue, true)) && is_array($cacheConfigs)) {
                $configs = $cacheConfigs;
                $reloadFlag = false;
            }
        }
        $lastModified = self::getLastModify();
        if (!$reloadFlag) {
            if (empty($lastModified)) {
                $reloadFlag = true;
                $configs = array();
            }elseif($lastModified!=$cache->get(self::MODIFY_CACHE_KEY))
            {
                $reloadFlag = true;
                $configs = array();
            }
        }
        if (empty($lastModified))
        {
            $lastModified = time();
        }
        //reload configs from db and set it to cache for 3600s
        if ($reloadFlag) {
            $reader = new ChannelConfigReader($type);
            $reader->setOrder('level');
            $channelConfigs = MsggConfig::readConfigs($reader);

            foreach ($channelConfigs as $channelConfig) {
                if ($config = $channelConfig->getChannelConfig()) {
                    $configs[] = $config;
                }
            }
            if (!empty($cache)) {
                $cache->set($cacheKey, json_encode($configs), 3600);
                $cache->set(self::MODIFY_CACHE_KEY, $lastModified);
            }
        }
        $results = array();
        foreach ($configs as $config) {
            $matchLevel = self::util_array_get($config, 'match_level', 0);
            if ($level >= $matchLevel) {
                $results[] = $config;
            }
        }
        return $results;
    }

}